package com.lcxw.hxzb.friendcircle.project.system.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.lcxw.hxzb.friendcircle.common.utils.BargainUtils;
import com.lcxw.hxzb.friendcircle.common.utils.DoubleUtil;
import com.lcxw.hxzb.friendcircle.framework.web.controller.BaseController;
import com.lcxw.hxzb.friendcircle.framework.web.domain.AjaxResult;
import com.lcxw.hxzb.friendcircle.framework.web.page.TableDataInfo;
import com.lcxw.hxzb.friendcircle.project.system.domain.*;
import com.lcxw.hxzb.friendcircle.project.system.mapper.VipBuyDetailMapper;
import com.lcxw.hxzb.friendcircle.project.system.mapper.YwpdChargeDetailMapper;
import com.lcxw.hxzb.friendcircle.project.system.mapper.YwpdMemberMapper;
import com.lcxw.hxzb.friendcircle.project.system.service.IYwpdBargainService;
import com.lcxw.hxzb.friendcircle.project.system.service.IYwpdBargainingService;
import com.lcxw.hxzb.friendcircle.project.system.service.VipBuyDetailService;
import com.lcxw.hxzbcommon.common.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 会员砍价Controller
 *
 * @author meeting
 * @date 2020-10-14
 */
@Api(description = "会员砍价Controller")
@RestController
@RequestMapping("/client/bargaining")
public class YwpdBargainingController extends BaseController {
    @Autowired
    private IYwpdBargainingService ywpdBargainingService;

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private IYwpdBargainService ywpdBargainService;

    @Autowired
    private WxMaService wxMaService;

    @Resource
    YwpdChargeDetailMapper ywpdChargeDetailMapper;


    @Resource
    VipBuyDetailService vipBuyDetailService;


    @Autowired
    YwpdMemberMapper ywpdMemberMapper;

    /**
     * 查询会员砍价列表
     */
    @ApiOperation("查询会员砍价列表")
    @GetMapping("/list")
    public TableDataInfo list(YwpdBargaining ywpdBargaining) {
        startPage();
        List<YwpdBargaining> list = ywpdBargainingService.selectYwpdBargainingList(ywpdBargaining);
        return getDataTable(list);
    }

    /**
     * 获取会员砍价详细信息
     */
    @ApiOperation("获取会员砍价详细信息")
    @GetMapping(value = "/{bargainingId}")
    public AjaxResult getInfo(@PathVariable("bargainingId") Long bargainingId) {
        return AjaxResult.success(ywpdBargainingService.selectYwpdBargainingById(bargainingId));
    }

    /**
     * 新增会员砍价
     */
    @ApiOperation("新增会员砍价")
    @PostMapping
    public AjaxResult add(@RequestBody YwpdBargaining ywpdBargaining) {
        ywpdBargaining.setMoney(9.9);
        ywpdBargaining.setSurplus(9.9);
        ywpdBargaining.setStatus("1");
        int total = new java.util.Random().nextInt(10) + 20;
        Object[] arrStr = BargainUtils.buildPriceArr(total, 9.9);
        ywpdBargaining.setDatas(Arrays.toString(arrStr));
        ywpdBargaining.setTotal(total);
        ywpdBargainingService.insertYwpdBargaining(ywpdBargaining);
        return AjaxResult.success(ywpdBargaining.getBargainingId());
    }


    /**
     */
    @ApiOperation("是否有正在砍价的活动")
    @PostMapping("/bargain")
    public AjaxResult post(@RequestBody YwpdBargaining ywpdBargaining) {
        ywpdBargaining.setStatus("1");
        List<YwpdBargaining> list = ywpdBargainingService.selectYwpdBargainingList(ywpdBargaining);
        if(list.isEmpty()){
            return  AjaxResult.success();
        }else{
            return AjaxResult.success(list.get(0));
        }
    }





    /**
     * 修改会员砍价
     */
    @ApiOperation("会员砍价")
    @PostMapping("/reduce")
    @Transactional
    public AjaxResult edit(@RequestBody YwpdBargaining ywpdBargaining) throws ParseException {
        YwpdBargain bargain = new YwpdBargain();
        bargain.setUserId(ywpdBargaining.getUserId());
        bargain.setBargainingId(ywpdBargaining.getBargainingId());
        List<YwpdBargain> list = ywpdBargainService.selectYwpdBargainList(bargain);
        if (!list.isEmpty()) {
            return AjaxResult.error("您已经砍过了");
        }
        YwpdBargaining old = ywpdBargainingService.selectYwpdBargainingById(ywpdBargaining.getBargainingId());
        if ("2".equals(old.getStatus()) || "3".equals(old.getStatus())) {
            return AjaxResult.error("砍价已经成功了");
        }
        JSONArray jsonArray = JSONArray.parseArray(old.getDatas());
        YwpdBargain search = new YwpdBargain();
        search.setBargainingId(ywpdBargaining.getBargainingId());
        List<YwpdBargain> lists = ywpdBargainService.selectYwpdBargainList(search);
        //更新剩余金额
        Double value = Double.valueOf(jsonArray.get(lists.size()) + "");
        old.setSurplus(DoubleUtil.sub(old.getSurplus(), value));
        //判断是不是最后一次砍价，如果是则更新砍价状态
        if(0==old.getSurplus().compareTo(new Double(0.0))){
            old.setStatus("2");
        }
        ywpdBargainingService.updateYwpdBargaining(old);
        //添加砍价明细
        YwpdBargain ywpdBargain = new YwpdBargain();
        ywpdBargain.setMoney(value);
        ywpdBargain.setBargainingId(ywpdBargaining.getBargainingId());
        ywpdBargain.setUserId(ywpdBargaining.getUserId());
        ywpdBargainService.insertYwpdBargain(ywpdBargain);
        //说明是最后一次砍价,给用户赋予会员权限
        if (lists.size() + 1 == old.getTotal()) {
            YwpdMember ywpdMember = ywpdMemberMapper
                    .selectYwpdMemberByUserId(old.getUserId());
            ywpdMember.setVip(1);
            String vipExpire = ywpdMember.getVipExpire();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StringUtil.isEmpty(vipExpire)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.add(Calendar.MONTH, 1);
                Date date = calendar.getTime();
                vipExpire = sdf.format(date);
            } else {
                Date date = sdf.parse(vipExpire);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.MONTH, 1);
                date = calendar.getTime();
                vipExpire = sdf.format(date);
            }
            ywpdMember.setVipExpire(vipExpire);
            ywpdMemberMapper.updateYwpdMember(ywpdMember);
        }
        return AjaxResult.success(value);
    }

    /**
     * 删除会员砍价
     */
    @ApiOperation("删除会员砍价")
    @DeleteMapping("/{bargainingIds}")
    public AjaxResult remove(@PathVariable Long[] bargainingIds) {
        return toAjax(ywpdBargainingService.deleteYwpdBargainingByIds(bargainingIds));
    }


    @ApiOperation("支付剩余金额")
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody YwpdBargaining ywpdBargaining) {
        if(null!=ywpdBargaining||null!=ywpdBargaining.getBargainingId()){
            YwpdBargaining bargaining=ywpdBargainingService.selectYwpdBargainingById(ywpdBargaining.getBargainingId());
            if(!"1".equals(bargaining.getStatus())){
                return AjaxResult.error("");
            }
            String sessionKey = null;
            String openId = null;
            try {
                WxMaJscode2SessionResult result = this.wxMaService.getUserService().getSessionInfo(ywpdBargaining.getCode());
                sessionKey = result.getSessionKey();
                openId = result.getOpenid();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (sessionKey == null || openId == null) {
                return AjaxResult.error("获取信息错误!");
            }
            String outTradeNo = "h"+bargaining.getBargainingId();
            WxPayMpOrderResult result = null;
            try {
                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                orderRequest.setOutTradeNo(outTradeNo);
                orderRequest.setBody("会员订单");
                int fee = 0;
                BigDecimal actualPrice = new BigDecimal(bargaining.getSurplus());
                fee = actualPrice.multiply(new BigDecimal(100)).intValue();
                orderRequest.setTotalFee(fee);
                orderRequest.setOpenid(openId);
                orderRequest.setSpbillCreateIp("127.0.0.1");
                orderRequest.setNotifyUrl("http://ywpd.natapp1.cc/manage/client/bargaining/callback");
                result  = wxPayService.createOrder(orderRequest);
                //开始生成一条充值记录，插入到数据库中
                YwpdChargeDetail ywpdChargedetail = new YwpdChargeDetail();
                ywpdChargedetail.setUserId(bargaining.getUserId());
                ywpdChargedetail.setOrderNo(outTradeNo);//我们的orderNo对应支付宝的outTradeNo
                ywpdChargedetail.setChargeMode("微信");
                ywpdChargedetail.setRmb(Float.valueOf(bargaining.getSurplus()+""));
                ywpdChargedetail.setCoin(0);
                ywpdChargedetail.setContent("小程序砍价会员订单");
                ywpdChargedetail.setStatus("创建交易");
                ywpdChargedetail.setProxyUId(null);
                ywpdChargedetail.setDealId(null);
                ywpdChargeDetailMapper.addChargeDetail(ywpdChargedetail);
                VipBuyDetail vipBuyDetail = new VipBuyDetail();
                vipBuyDetail.setOrderNo(outTradeNo);
                vipBuyDetail.setUserId(bargaining.getUserId());
                vipBuyDetail.setVipType("month");
                vipBuyDetail.setAddTime(StringUtil.getDateTime());
                vipBuyDetail.setStatus("0");
                vipBuyDetailService.save(vipBuyDetail);
                return AjaxResult.success(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.error("系统错误");
    }


    @ApiOperation("充值接口")
    @PostMapping("/recharge")
    public AjaxResult recharge(@RequestBody YwpdChargeDetail detail) {
        if(null!=detail){
            String sessionKey = null;
            String openId = null;
            try {
                WxMaJscode2SessionResult result = this.wxMaService.getUserService().getSessionInfo(detail.getCode());
                sessionKey = result.getSessionKey();
                openId = result.getOpenid();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (sessionKey == null || openId == null) {
                return AjaxResult.error("获取信息错误!");
            }
            WxPayMpOrderResult result = null;
            try {
                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                String outTradeNo = "h"+StringUtil.getOrderIdByUUId(1);
                orderRequest.setOutTradeNo(outTradeNo);
                orderRequest.setBody("会员订单");
                int fee = 0;
                BigDecimal actualPrice = new BigDecimal(detail.getRmb());
                fee = actualPrice.multiply(new BigDecimal(100)).intValue();
                orderRequest.setTotalFee(fee);
                orderRequest.setOpenid(openId);
                orderRequest.setSpbillCreateIp("127.0.0.1");
                orderRequest.setNotifyUrl("http://ywpd.natapp1.cc/manage/client/bargaining/callback");
                result  = wxPayService.createOrder(orderRequest);
                //开始生成一条充值记录，插入到数据库中
                YwpdChargeDetail ywpdChargedetail = new YwpdChargeDetail();
                ywpdChargedetail.setUserId(detail.getUserId());
                ywpdChargedetail.setOrderNo(outTradeNo);//我们的orderNo对应支付宝的outTradeNo
                ywpdChargedetail.setChargeMode("微信");
                ywpdChargedetail.setRmb((float) detail.getRmb());
                ywpdChargedetail.setCoin(detail.getCoin());
                ywpdChargedetail.setStatus("创建交易");
                ywpdChargedetail.setProxyUId(null);
                ywpdChargedetail.setDealId(null);
                ywpdChargeDetailMapper.addChargeDetail(ywpdChargedetail);
                return AjaxResult.success(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.error("系统错误");
    }

    /**
     * 新增服务
     */
    @PostMapping("callback")
    @Transactional
    public Object callback(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        System.out.println("微信支付授权回调");
        String xmlResult = null;
        try {
            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail(e.getMessage());
        }
        WxPayOrderNotifyResult result = null;
        try {
            result = wxPayService.parseOrderNotifyResult(xmlResult);
            if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode())){
                logger.error(xmlResult);
                throw new WxPayException("微信通知支付失败！");
            }
            if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())){
                logger.error(xmlResult);
                throw new WxPayException("微信通知支付失败！");
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail(e.getMessage());
        }
        logger.info("处理腾讯支付平台的订单支付");
        String outTradeNo = result.getOutTradeNo();
        //h开始的订单为砍价会员订单
        if(outTradeNo.startsWith("h")){
            YwpdBargaining bargaining=ywpdBargainingService.selectYwpdBargainingById(Long.valueOf(outTradeNo.substring(1, outTradeNo.length())));
            bargaining.setStatus("3");
            ywpdBargainingService.updateYwpdBargaining(bargaining);
            QueryWrapper<VipBuyDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(VipBuyDetail::getOrderNo, outTradeNo);
            VipBuyDetail vipBuyDetail = vipBuyDetailService.getOne(queryWrapper);
            vipBuyDetail.setStatus("1");
            vipBuyDetailService.updateById(vipBuyDetail);
            YwpdMember ywpdMember = ywpdMemberMapper
                    .selectYwpdMemberByUserId(vipBuyDetail.getUserId());
            ywpdMember.setVip(1);
            String vipExpire = ywpdMember.getVipExpire();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StringUtil.isEmpty(vipExpire)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                if (vipBuyDetail.getVipType().equals("month")) {
                    calendar.add(Calendar.MONTH, 1);
                } else {
                    calendar.add(Calendar.YEAR, 1);
                }
                Date date = calendar.getTime();
                vipExpire = sdf.format(date);
            } else {
                Date date = sdf.parse(vipExpire);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                if (vipBuyDetail.getVipType().equals("month")) {
                    calendar.add(Calendar.MONTH, 1);
                } else {
                    calendar.add(Calendar.YEAR, 1);
                }
                date = calendar.getTime();
                vipExpire = sdf.format(date);
            }
            ywpdMember.setVipExpire(vipExpire);
            ywpdMemberMapper.updateYwpdMember(ywpdMember);
        }
        //c开始的订单为充值幸运币订单
        if(outTradeNo.startsWith("c")){
            String return_code = result.getReturnCode();
            String return_msg = result.getReturnMsg();
            String result_code = result.getResultCode();
            String thirdOrderNo = result.getTransactionId();
            String orderNo = result.getOutTradeNo();
            String chargeTime = result.getTimeEnd();
            String thirdBuyerAccount = result.getOpenid();
            String thirdSellerAccount = result.getMchId();
            if (return_code.equals("SUCCESS") && result_code.equals("SUCCESS")) {
                YwpdChargeDetail ywpdChargedetail = ywpdChargeDetailMapper.selectByOrderNo(orderNo);
                ywpdChargedetail.setThirdOrderNo(thirdOrderNo);
                ywpdChargedetail.setChargeTime(chargeTime);
                ywpdChargedetail.setThirdBuyerAccount(thirdBuyerAccount);
                ywpdChargedetail.setThirdSellerAccount(thirdSellerAccount);
                ywpdChargedetail.setThirdBuyerEmail(null);
                ywpdChargedetail.setThirdSellerEmail(null);
                ywpdChargedetail.setStatus("交易成功");
                ywpdChargeDetailMapper.updateStatusByOrderNo(ywpdChargedetail);
                //完成支付后，将用户充进的虚拟货币添加到用户数据中
                ywpdMemberMapper .updateCoinByUserId(ywpdChargedetail.getCoin(), ywpdChargedetail.getUserId());
            }
        }
        return WxPayNotifyResponse.success("处理成功!");
    }

}
